// ==UserSubscribe==
// @name         自动采集商品数据（手动/自动模式开关）
// @namespace    http://tampermonkey.net/
// @version      1.9.2
// @description  支持手动/自动滚动采集，关键词模糊匹配筛选，软弹窗交互。
// @author       子风
// @match        https://s.taobao.com/search?*
// @grant        GM_xmlhttpRequest
// @grant        GM_download
// @grant        GM_setClipboard
// @require      https://cdn.jsdelivr.net/npm/xlsx/dist/xlsx.full.min.js
// @scriptUrl    https://gitee.com/chuzifeng/script-cat-script/raw/master/%E6%B7%98%E5%AE%9D%E5%BA%97%E9%93%BA%E9%87%87%E9%9B%86%E5%99%A8.js
// ==/UserSubscribe==

(function () {
    'use strict';

    let countDisplay, filteredCountDisplay, keywordInput, dataList = [];
    let manualMode = false, autoMode = false;
    let panel, toggleButton;

    // 创建 UI 面板
    function createUIPanel() {
        panel = document.createElement("div");
        panel.style.position = "fixed";
        panel.style.top = "10px";
        panel.style.right = "10px";
        panel.style.zIndex = "9999";
        panel.style.background = "rgba(0, 0, 0, 0.8)";
        panel.style.color = "white";
        panel.style.padding = "20px";
        panel.style.borderRadius = "10px";
        panel.style.fontSize = "14px";
        panel.style.display = "flex";
        panel.style.flexDirection = "column";
        panel.style.gap = "15px";
        panel.style.boxShadow = "0 0 15px rgba(0, 0, 0, 0.5)";
        panel.style.width = "300px";

        // 标题
        let title = document.createElement("h2");
        title.innerText = "淘宝店铺采集器";
        title.style.margin = "0";
        title.style.fontSize = "18px";
        title.style.fontWeight = "bold";
        title.style.textAlign = "center";
        panel.appendChild(title);

        // 关键词输入框
        keywordInput = document.createElement("input");
        keywordInput.type = "text";
        keywordInput.placeholder = "输入关键词筛选（模糊匹配）";
        keywordInput.style.padding = "10px";
        keywordInput.style.borderRadius = "5px";
        keywordInput.style.border = "1px solid #ccc";
        keywordInput.style.fontSize = "14px";
        keywordInput.style.marginBottom = "10px";
        keywordInput.style.width = "100%";
        panel.appendChild(keywordInput);

        // 总数据量显示
        countDisplay = document.createElement("div");
        countDisplay.innerText = "总数据量：0 条";
        countDisplay.style.textAlign = "center";
        panel.appendChild(countDisplay);

        // 过滤后数据量显示
        filteredCountDisplay = document.createElement("div");
        filteredCountDisplay.innerText = "过滤后数据量：0 条";
        filteredCountDisplay.style.textAlign = "center";
        panel.appendChild(filteredCountDisplay);

        // 手动采集开关
        let manualButton = document.createElement("button");
        manualButton.innerText = "手动采集：关闭";
        manualButton.style.padding = "10px";
        manualButton.style.borderRadius = "5px";
        manualButton.style.border = "none";
        manualButton.style.background = "#4CAF50";
        manualButton.style.color = "white";
        manualButton.style.cursor = "pointer";
        manualButton.style.fontSize = "14px";
        manualButton.onclick = function () {
            manualMode = !manualMode;
            manualButton.innerText = `手动采集：${manualMode ? "开启" : "关闭"}`;
            manualButton.style.backgroundColor = manualMode ? "#f44336" : "#4CAF50";
        };
        panel.appendChild(manualButton);

        // 自动采集开关
        let autoButton = document.createElement("button");
        autoButton.innerText = "自动采集：关闭";
        autoButton.style.padding = "10px";
        autoButton.style.borderRadius = "5px";
        autoButton.style.border = "none";
        autoButton.style.background = "#2196F3";
        autoButton.style.color = "white";
        autoButton.style.cursor = "pointer";
        autoButton.style.fontSize = "14px";
        autoButton.onclick = async function () {
            autoMode = !autoMode;
            autoButton.innerText = `自动采集：${autoMode ? "开启" : "关闭"}`;
            autoButton.style.backgroundColor = autoMode ? "#f44336" : "#2196F3";
            if (autoMode) {
                await autoScroll();
            }
        };
        panel.appendChild(autoButton);

        // 下载 Excel 按钮
        let downloadButton = document.createElement("button");
        downloadButton.innerText = "下载 Excel";
        downloadButton.style.padding = "10px";
        downloadButton.style.borderRadius = "5px";
        downloadButton.style.border = "none";
        downloadButton.style.background = "#FF9800";
        downloadButton.style.color = "white";
        downloadButton.style.cursor = "pointer";
        downloadButton.style.fontSize = "14px";
        downloadButton.onclick = () => downloadExcel(dataList);
        panel.appendChild(downloadButton);

        // 创建面板和按钮并排的容器
        let container = document.createElement("div");
        container.style.position = "fixed";
        container.style.top = "10px";
        container.style.right = "10px";
        container.style.display = "flex";
        container.style.alignItems = "flex-start";  // Align buttons and panel vertically
        container.style.zIndex = "9999";

        // 将面板添加到容器中
        container.appendChild(panel);

        // 创建面板开关按钮并将其添加到容器
        toggleButton = document.createElement("button");
        toggleButton.innerText = "打开面板";
        toggleButton.style.position = "absolute";
        toggleButton.style.top = "10px";
        toggleButton.style.right = "10px"; // 默认为贴近右边
        toggleButton.style.zIndex = "10000";
        toggleButton.style.padding = "10px";
        toggleButton.style.borderRadius = "50%"; // 圆形按钮
        toggleButton.style.border = "none";
        toggleButton.style.background = "#333";
        toggleButton.style.color = "white";
        toggleButton.style.cursor = "pointer";
        toggleButton.style.fontSize = "14px";
        toggleButton.style.transition = "all 0.3s";  // 动画效果，按钮圆角平滑变化
        toggleButton.onclick = function () {
            if (panel.style.display === "none") {
                panel.style.display = "flex";
                toggleButton.innerText = "关闭面板";
                // 面板显示时，按钮靠近面板左侧
                toggleButton.style.right = "calc(100% + 10px)";
                toggleButton.style.borderRadius = "50% 0 0 50%"; // 圆角效果
            } else {
                panel.style.display = "none";
                toggleButton.innerText = "打开面板";
                // 面板隐藏时，按钮贴近网页右侧
                toggleButton.style.right = "10px";
                toggleButton.style.borderRadius = "50%"; // 圆形按钮
            }
        };
        container.appendChild(toggleButton);

        // 添加到页面中
        document.body.appendChild(container);
    }



    // 自动滚动加载（翻页）
    async function autoScroll() {
        let lastHeight = 0;
        let retries = 0;
        while (autoMode && retries < 5) {
            window.scrollTo(0, document.body.scrollHeight);
            await new Promise(resolve => setTimeout(resolve, 2000));
            let newHeight = document.body.scrollHeight;
            if (newHeight === lastHeight) {
                retries++;
            } else {
                retries = 0;
                lastHeight = newHeight;
            }
            extractData();
        }
        console.log("自动滚动结束，采集数据完成");
    }

    // 采集数据
    function extractData() {
        let keyword = keywordInput.value.trim();
        let keywordRegex = convertKeywordToRegex(keyword);

        let items = document.querySelectorAll("a[href^='//shop']");
        items.forEach(item => {
            let titleEl = item.querySelector("[class^='title--']");
            let title = titleEl ? titleEl.innerText.trim() : "无标题";
            let link = "https:" + item.getAttribute("href");

            // 总数据量更新
            if (!dataList.some(data => data["商品链接"] === link)) {
                dataList.push({ "商品标题": title, "商品链接": link });
            }
        });

        // 更新总数据量显示
        countDisplay.innerText = `总数据量：${dataList.length} 条`;

        // 更新筛选后数据量显示
        let filteredData = filterData(dataList, keywordRegex);
        filteredCountDisplay.innerText = `过滤后数据量：${filteredData.length} 条`;
        console.log("筛选后的数据：", filteredData);
    }

    // 转换用户输入的关键词为正则表达式
    function convertKeywordToRegex(keyword) {
        // 将 '*' 替换为 '.*'，表示模糊匹配中间的任意字符
        let regexStr = keyword.replace(/\*/g, ".*");
        return new RegExp(regexStr, "i");  // 使用不区分大小写的正则表达式
    }

    // 筛选数据
    function filterData(data, keywordRegex) {
        if (!keywordRegex) return data; // 如果没有关键词，返回所有数据
        return data.filter(item => keywordRegex.test(item["商品标题"]));
    }

    // 监听用户滚动（仅在手动模式下采集）
    window.addEventListener("scroll", function () {
        if (manualMode) {
            extractData();
        }
    });


    // 下载 Excel
    function downloadExcel(data) {
        if (data.length === 0) {
            alert("没有符合条件的数据可以下载！");
            return;
        }

        // 创建 Excel 工作簿
        let wb = XLSX.utils.book_new();

        // 未筛选的数据
        let originalData = [...data];  // 复制一份原始数据
        let wsOriginal = XLSX.utils.json_to_sheet(originalData);
        XLSX.utils.book_append_sheet(wb, wsOriginal, "未筛选数据");

        // 获取关键词正则表达式
        let keyword = keywordInput.value.trim();
        let keywordRegex = convertKeywordToRegex(keyword);

        // 筛选后的数据
        let filteredData = filterData(originalData, keywordRegex);  // 使用筛选功能
        let wsFiltered = XLSX.utils.json_to_sheet(filteredData);
        XLSX.utils.book_append_sheet(wb, wsFiltered, "筛选后数据");

        // 写入 Excel 文件
        let wbout = XLSX.write(wb, { bookType: "xlsx", type: "array" });
        let blob = new Blob([wbout], { type: "application/octet-stream" });

        let a = document.createElement("a");
        a.href = URL.createObjectURL(blob);
        a.download = "商品数据.xlsx";
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        console.log("Excel 文件已下载");
    }


    // 初始化
    createUIPanel();
})();
